package com.tinem.platform.service.user.api;

import com.tinem.platform.module.commons.util.SessionUtil;
import com.tinem.platform.module.pojo.vo.IdBlankVo;
import com.tinem.platform.module.starter.jpa.entity.oauth.UserSessionToken;
import com.tinem.platform.module.starter.jpa.repository.oauth2.UserSessionTokenRepository;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/session")
public class SessionApi {


    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    UserSessionTokenRepository userSessionTokenRepository;

    @RequestMapping("/add.api")
    public Object add(@RequestBody UserSessionToken userSessionToken){
        return userSessionTokenRepository.saveAndFlush(userSessionToken);
    }


    @RequestMapping("/getAllSessionByUser.api")
    public Object getAllSessionByUser(@RequestBody IdBlankVo userId){
        return getAllSessionByUser(userId.getUuidToId()).collect(Collectors.toList());
    }

    /**
     *
     * 删除用户所有session
     * @param userId
     * @return
     */
    @RequestMapping("/delAllSessionByUser.api")
    public Object delAllSessionByUser(@RequestBody IdBlankVo userId){
        List<String> sessionIds = getAllSessionByUser(userId.getUuidToId())
                .map(UserSessionToken::getId)
                .map(SessionUtil::getRedisKeySessionId)
                .collect(Collectors.toList());
        return stringRedisTemplate.delete(sessionIds);
    }

    private Stream<UserSessionToken> getAllSessionByUser(String userId){
        return userSessionTokenRepository.findByUserIdAndExpAfter(userId,new Date())
                .stream()
                .filter(userSessionToken -> stringRedisTemplate.hasKey(SessionUtil.getRedisKeySessionId(userSessionToken.getId())));
    }
}
